<template>
  <div class="personal-affairs">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个人事务</span>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            添加事务
          </el-button>
        </div>
      </template>

      <!-- 事务列表 -->
      <el-table
        v-loading="loading"
        :data="affairs"
        style="width: 100%;"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="affairName" label="事务名称" />
        <el-table-column prop="affairCode" label="事务编号" width="180" />
        <el-table-column prop="startDate" label="开始日期" width="140" />
        <el-table-column prop="endDate" label="结束日期" width="140" />
        <el-table-column prop="completionRating" label="完成度评级" width="120" />
        <!-- 新增：操作列 -->
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增事务对话框 -->
    <el-dialog v-model="showAddDialog" title="添加个人事务" width="500px" @close="resetForm">
      <el-form ref="affairFormRef" :model="affairForm" :rules="affairRules" label-width="100px">
        <!-- 新增：事务库项选择 -->
        <el-form-item label="事务库项">
          <el-select
            v-model="selectedCatalogCode"
            placeholder="请选择或搜索事务库项"
            filterable
            clearable
            style="width: 100%;"
            @change="handleCatalogSelect"
          >
            <el-option
              v-for="item in catalogItems"
              :key="item.code"
              :label="`${item.code}-${item.categoryName}-${item.itemName}`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <!-- 原有表单字段 -->
        <el-form-item label="事务名称" prop="affairName">
          <el-input v-model="affairForm.affairName" placeholder="请输入事务名称" clearable />
        </el-form-item>
        <el-form-item label="事务编号" prop="affairCode">
          <el-input v-model="affairForm.affairCode" placeholder="请输入事务编号" clearable />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="affairForm.startDate" type="datetime" placeholder="选择开始日期时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="affairForm.endDate" type="datetime" placeholder="选择结束日期时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="完成度评级" prop="completionRating">
          <el-select v-model="affairForm.completionRating" placeholder="请选择评级">
            <el-option v-for="n in 5" :key="n" :label="n" :value="n" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { personalApi } from '@/api/personal'
// 新增：事务库API
import { catalogApi } from '@/api/catalog'

export default {
  name: 'PersonalAffairs',
  components: { Plus },
  setup() {
    const store = useStore()
    const loading = ref(false)
    const affairs = ref([])
    const showAddDialog = ref(false)
    const submitLoading = ref(false)
    const affairFormRef = ref(null)

    // 事务库相关状态
    const catalogItems = ref([])
    const selectedCatalogCode = ref(null)

    const affairForm = reactive({
      userId: null,
      affairName: '',
      affairCode: '',
      startDate: null,
      endDate: null,
      completionRating: 3
    })

    const affairRules = {
      affairName: [{ required: true, message: '请输入事务名称', trigger: 'blur' }],
      affairCode: [{ required: true, message: '请输入事务编号', trigger: 'blur' }],
      startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
      endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
      completionRating: [{ required: true, message: '请选择完成度评级', trigger: 'change' }]
    }

    const loadAffairs = async () => {
      const currentUser = store.getters.currentUser
      if (!currentUser) return
      loading.value = true
      try {
        const response = await personalApi.affairs.getAffairs(currentUser.id)
        // 兼容ApiResponse和原始列表两种返回结构
        const data = response?.data?.data ?? response?.data
        affairs.value = Array.isArray(data) ? data : []
      } catch (error) {
        ElMessage.error('加载个人事务失败')
      } finally {
        loading.value = false
      }
    }

    // 加载事务库项
    const loadCatalogItems = async () => {
      try {
        const response = await catalogApi.getItems()
        const list = response?.data
        catalogItems.value = Array.isArray(list) ? list : []
      } catch (err) {
        catalogItems.value = []
      }
    }

    const resetForm = () => {
      affairForm.userId = store.getters.currentUser?.id || null
      affairForm.affairName = ''
      affairForm.affairCode = ''
      affairForm.startDate = null
      affairForm.endDate = null
      affairForm.completionRating = 3
      selectedCatalogCode.value = null
    }

    // 选择库项后联动填充表单
    const handleCatalogSelect = (val) => {
      const item = catalogItems.value.find(i => i.code === val)
      if (item) {
        affairForm.affairCode = item.code // 例如 1-1
        affairForm.affairName = item.itemName // 例如 与孩子交谈
      }
    }

    const handleSubmit = () => {
      affairFormRef.value.validate(async (valid) => {
        if (!valid) return
        submitLoading.value = true
        try {
          affairForm.userId = store.getters.currentUser?.id || null
          const payload = { ...affairForm }
          const response = await personalApi.affairs.createAffair(payload)
          if (response.data.code === 200) {
            ElMessage.success('创建成功')
            showAddDialog.value = false
            resetForm()
            loadAffairs()
          } else {
            ElMessage.error(response.data.message || '创建失败')
          }
        } catch (error) {
          ElMessage.error('创建失败')
        } finally {
          submitLoading.value = false
        }
      })
    }

    // 新增：删除处理
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(`确认删除事务「${row.affairName}」？`, '提示', {
          type: 'warning',
          confirmButtonText: '删除',
          cancelButtonText: '取消'
        })
        await personalApi.affairs.deleteAffair(row.id)
        ElMessage.success('删除成功')
        loadAffairs()
      } catch (error) {
        // 取消不会提示错误，其他错误提示删除失败
        if (String(error) !== 'cancel' && String(error) !== 'close') {
          ElMessage.error('删除失败')
        }
      }
    }

    onMounted(() => {
      resetForm()
      loadAffairs()
      loadCatalogItems()
    })

    return {
      loading,
      affairs,
      showAddDialog,
      submitLoading,
      affairFormRef,
      affairForm,
      affairRules,
      handleSubmit,
      resetForm,
      // 事务库相关绑定
      catalogItems,
      selectedCatalogCode,
      handleCatalogSelect,
      // 新增：删除
      handleDelete
    }
  }
}
</script>

<style scoped>
.personal-affairs {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>